package com.zust.ysc012.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;

import static com.zust.ysc012.dao.PublicDao.deleteNowUser;

/**
 * @Description
 * @Author Mato
 * @Date 04/07/2021 02:52
 */
@WebServlet(urlPatterns = "/logoutServlet")
public class LogoutServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            Cookie cookie;
            Cookie cookies[]=req.getCookies();
            for ( int  i= 0 ; i<cookies.length- 1; i++){    //用一个循环语句遍历刚才建立的Cookie对象数组
                cookie = cookies[i];   //取出数组中的一个Cookie对象
                if (cookie != null ){
                    cookies[i].setMaxAge(0);
                    resp.addCookie(cookies[i]);
                }
            }
            HttpSession session = req.getSession(true);
            session.invalidate();
            deleteNowUser();
            req.getRequestDispatcher("index.jsp").forward(req,resp);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
